import Vue from "vue";
import VueRouter from "vue-router";
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'

// 添加组件
import { GET } from "@/util/Axios.js";

Vue.use(VueRouter);
// 2023-03-16 17:01:42
// 添加路由组件

const router = new VueRouter({
    routes: [
        {
            path: '*',
            redirect: '/main'
        },
        {
            path: '',
            redirect: '/main',
        },
        {
            name: 'main',
            path: '/main',
            component: () => import('@/page/mainPage.vue'),
            meta: {
                isDefault: true
            }
        },
        {
            path: '/error',
            name: 'error',
            component: () => import('@/page/errorPage.vue')
        },
        {
            path: '/login',
            name: 'login',
            component: () => import('@/page/loginPage.vue')
        },
        {
            path: '/register',
            name: 'register',
            component: () => import('@/page/registerPage.vue')
        }
    ]
})


//去掉路由重复的报错
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
    try {
        return originalPush.call(this, location).catch(err => err)
    } catch (error) {

    }
}


router.beforeEach(async (to, from, next) => {
    nprogress.start();
    if (to.name != 'login' && to.name != 'register' && to.name != 'error') {
        // 不是跳转login都是要鉴权
        try {
            await GET('/base/checkToken')
            next()
            return
        } catch (error) {
            // token无效
            if (error && error.data && error.data.code == '401') {
                next({
                    name: 'login'
                })
                nprogress.done()
                return
            }
            // 其他报错
            else {
                console.log(error);
                next({
                    name: 'error'
                })
                return
            }
        }
    } else {
        next()
    }
})
router.afterEach((to, from) => {
    nprogress.done()
})
export default router;
